<?php


namespace App\HttpController\Service;


use App\Exceptions\ApiException;
use App\Model\UserPointLogModel;
use App\Model\UserProfileModel;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;

class PointService
{


    public static function addPoint($user_id, $point, $type, $desc = '')
    {
        try {

            DbManager::getInstance()->startTransaction();
            $field = $type == 1 ? 'common_point' : ($type == 2 ? 'specialify_point' : '');
            if(!$field) throw new ApiException('积分类型错误！');

            # 更新表内积分
            UserProfileModel::create()->where(['user_id' => $user_id])->update(
                [
                    $field => QueryBuilder::inc($point)
                ]
            );

            $point_log = UserPointLogModel::create(
                [
                    'user_id' => $user_id,
                    'type' => $type,
                    'point' => $point,
                    'create_time' => time(),
                    'desc' => $desc
                ]
            );
            $point_log->save();
            DbManager::getInstance()->commit();
        } catch (Exception $e) {
            DbManager::getInstance()->rollback();
            throw new ApiException($e->getMessage());
        }

    }

}